import React,{ useCallback,useState,useEffect,useMemo } from 'react';
import { PermissionsAndroid } from 'react-native';
import ApolloClient from 'apollo-boost';
import {InMemoryCache} from 'apollo-boost'
import * as config from '../../AppConfig';
import NetInfo from '@react-native-community/netinfo';
import Geolocation from '@react-native-community/geolocation';
import DeviceInfo from 'react-native-device-info';

import { GQL,AllForOne} from './graphql/index.js';
export { GQL,AllForOne };

export function clientBuilder(token: string){
    
    const createClient = useCallback( (token) => {
        let client =  new ApolloClient({
            cache: new InMemoryCache(),
            uri: config.ServerUri + '/gql',
            request: async (operation) => {
                const granted = await PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                    {
                      title: '申请位置权限',
                      message:
                        '一个很牛逼的应用想了解你所在的城市，' +
                        '然后你就可以同城交友了',
                      buttonNegative: '去你的🙃',
                      buttonPositive: '可以的',
                    },
                  );

                let netInfo = await NetInfo.fetch();
                let brand = DeviceInfo.getBrand();
                let mac = DeviceInfo.getMacAddressSync();
                let uuid = DeviceInfo.getUniqueId();
                let system = DeviceInfo.getSystemName();
                let systemVersion = DeviceInfo.getSystemVersion();
                let emulator = DeviceInfo.isEmulatorSync();
 
                var longitude = "";
                var latitude = "";
                if(granted == "granted"){
                    await  Geolocation.getCurrentPosition(
                        location => {
                            longitude = location.coords.longitude.toString();
                            latitude = location.coords.latitude.toString();
                        }
                    );
                }
                let location = {longitude,latitude};

                operation.setContext({
                    headers: {
                        token,
                        Authorization: token ? `Bearer ${token}` : '',
                        network: netInfo.type,
                        location,
                        brand,
                        mac,
                        uuid,
                        system,
                        systemVersion,
                        emulator
                    }
                })
            },
            onError: ({graphQLErrors, networkError, operation, forward}) => {
                if (graphQLErrors) {
                    graphQLErrors.map(error => {
                        //
                    });
                }
                if (networkError) {
                    console.log("Apollo Client happened error on creating...: \n\t ",reason);
                }
            }
        });
        return client;
    },[]);

    const [client,setClient] = useState(() => createClient(token))

    useEffect(() => {
        const client = createClient(token);
        setClient(client);
    },[token]);

    return client;
   
}